package cc.rengu.igas.opms.common.util;

import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.RandomUtil;
import cc.rengu.oltp.utility.util.StringUtil;

public class StringBaseUtil {
    /**
     * 校验字符串是否为纯数字
     *
     * @param checkString
     * @return true-字符串为纯数字，false-字符串非纯数字
     */
    public static boolean isNumberic(String checkString) {
        if (null == checkString || checkString.isEmpty()) {
            return false;
        } else {
            return checkString.matches("^[0-9]*$");
        }
    }

    public static String genUserId() {
        return DateUtil.getCurrentDateTime("yyyyMMddHHmmss") + RandomUtil.randomNumStr(10);
    }

    /**
     * 脱敏
     *
     * @return
     */
    public static String convert(String fieldType, String sensitiveValue) {
        StringBuilder stringBuilder = new StringBuilder(sensitiveValue);
        String convertOutField;
        if ("1".equals(fieldType)) {   //手机号脱敏
            convertOutField = subStr(sensitiveValue, 3, sensitiveValue.length() - 4) + "|" + RandomUtil.getUUID();
        } else if ("2".equals(fieldType)) {  //银行卡账号脱敏
            convertOutField = subStr(sensitiveValue, 6, sensitiveValue.length() - 4) + "|" + RandomUtil.getUUID();
        } else if ("3".equals(fieldType)) {  //证件信息脱敏(脱敏出生日期)
            convertOutField = subStr(sensitiveValue, 6, sensitiveValue.length() - 4) + "|" + RandomUtil.getUUID();
        } else if ("4".equals(fieldType)) { //姓名脱敏
            convertOutField = subStr(sensitiveValue, 0, 1) + "|" + RandomUtil.getUUID();
        } else {
            convertOutField = stringBuilder.replace(4, sensitiveValue.length() - 4, "******") + "|" + RandomUtil.getUUID();
        }

        return convertOutField;
    }


    /**
     * 字符串截取
     *
     * @param sourceStr 待脱敏串
     * @param begin     开始位置
     * @param end       结束位置
     * @return 脱敏串
     */
    private static String subStr(String sourceStr, int begin, int end) {
        if (StringUtil.isEmptyOrNull(sourceStr) || begin > end) {
            return "";
        }
        if (begin == end) {
            return sourceStr.replaceFirst(sourceStr.substring(begin), "*");
        }
        StringBuffer stringBuffer = new StringBuffer(sourceStr.substring(0, begin));
        for (int index = begin; index < end; index++) {
            stringBuffer.append("*");
        }
        stringBuffer.append(sourceStr.substring(end));
        return stringBuffer.toString();
    }
}
